<template>
  <div class="events-management">
    <nav-header></nav-header>

    <div class="zh-table">
      <div class="zh-table-open clear">
        <div class="zh-open-left fl">
          <div class="open-width" style="width: 140px">
            <el-select v-model="listParam.levelType" filterable placeholder="请选择">
              <el-option
                v-for="(item, index) in typeOptons"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="open-width" style="width: 140px">
            <el-select v-model="listParam.status" filterable placeholder="请选择">
              <el-option
                v-for="(item, index) in statusOptons"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="open-width" style="width: 220px">
            <el-date-picker
              v-model="listParam.pickerTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator=" - "
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </div>
          <div class="open-width">
            <el-input
              v-model="listParam.keyword"
              @keyup.enter.native="searchFunc"
              placeholder="主题、地点、联系人"
            ></el-input>
          </div>
          <el-button type="primary" @click="searchFunc">搜索</el-button>
          <el-button type="primary" @click="resetList">重置</el-button>
        </div>
        <div class="zh-open-right fr">
          <el-button type="primary" @click="createEvents">创建赛事</el-button>
          <el-button type="danger" @click="dleteAllConfirm">批量删除</el-button>
        </div>
      </div>

      <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
        <el-table
          :data="listData"
          fixed
          border
          max-height="600"
          @selection-change="tableSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="50" align="center" fixed></el-table-column>
          <el-table-column
            prop="name"
            label="赛事主题"
            align="center"
            width="318"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="organizer"
            label="创建人"
            align="center"
            width="88"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column align="center" width="180" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.start_time + " 至 "+ scope.row.end_time }}</template>
          </el-table-column>
          <el-table-column label="赛事类型" align="center" width="100" show-overflow-tooltip>
            <template
              v-if="scope.row.level_type"
              slot-scope="scope"
            >{{ typeOptons[+scope.row.level_type].label }}</template>
          </el-table-column>
          <el-table-column
            prop="place"
            label="赛事地点"
            align="center"
            width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="responsibler"
            label="赛事联系人"
            align="center"
            width="100"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="telephone"
            label="联系电话"
            align="center"
            width="120"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="show_status_text"
            label="赛事状态"
            align="center"
            width="88"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                @click="setTop(scope.row.id)"
                type="text"
              >{{scope.row.top=='1'?'取消置顶':'置顶'}}</el-button>
              <!-- <el-button v-if="scope.row.status=='1'" @click="releaseResults(scope.row.id)" type="text">发布成绩</el-button> -->
              <template v-if="scope.row.status=='1'">
                <div class="release-results" @click="releaseResults(scope.row.id)">
                  <uploader
                    class="uploader-example"
                    ref="uploader"
                    :options="uploadOptions"
                    :file-status-text="statusText"
                    @file-success="fileSuccess"
                    @file-error="fileFail"
                  >
                    <uploader-unsupport></uploader-unsupport>
                    <uploader-drop>
                      <uploader-btn>发布成绩</uploader-btn>
                    </uploader-drop>
                  </uploader>
                </div>
              </template>
              <el-button @click="goDetail(scope.row.id)" type="text">详情</el-button>
              <el-button
                v-if="scope.row.status=='1'&&scope.row.online=='1'"
                @click="getAllData(scope.row.id)"
                type="text"
              >导出名单</el-button>
              <el-button @click="delActivity(scope.row.id)" type="text" class="delete-button">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-pagination" v-show="totalNumber > 10">
          <el-pagination
            @size-change="changeCurrentSize"
            @current-change="changeCurrentPage"
            :current-page="listParam.pageIndex"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="listParam.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalNumber"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import XLSX from "xlsx";
import FileSaver from "file-saver";
const defaultParam = {
  levelType: "-1", //活动类
  status: "-1", //活动状态
  pickerTime: [], //搜索条件的开始-结束日程
  keyword: "", //搜索的关键字
  // 分页：
  pageIndex: 1,
  pageSize: 10
};
export default {
  data() {
    return {
      typeOptons: [
        {
          value: "-1",
          label: "全部类型"
        },
        {
          value: "1",
          label: "校级赛事"
        },
        {
          value: "2",
          label: "年级赛事"
        },
        {
          value: "3",
          label: "班级赛事"
        }
      ],
      statusOptons: [
        {
          value: "-1",
          label: "全部状态"
        },
        {
          value: "1",
          label: "未开始"
        },
        {
          value: "2",
          label: "报名中"
        },
        {
          value: "3",
          label: "进行中"
        },
        {
          value: "4",
          label: "已结束"
        }
      ],
      userId: this.$g.user_id,
      // 获取活动列表接口的参数
      listParam: Object.assign({}, defaultParam),
      totalNumber: 0,
      selected: [], // 选中的数据
      listData: [{}],
      loading: {
        status: false,
        txt: "获取数据..."
      },
      uploadOptions: {
        target: this.BASE_URL + "/api/competition/vue_demo_upload",
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token }
      },
      statusText: {
        success: "上传成功",
        error: "上传出错",
        uploading: "正在上传...",
        paused: "暂停",
        waiting: "等待上传"
      },
      eventId: "" //发布成绩的赛事ID
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 创建赛事
     */
    createEvents() {
      this.$router.push("/life/events/create-events");
    },
    /**
     * 获取菜单管理列表
     */
    getList() {
      this.loading.status = true;
      let success = res => {
        this.loading.status = false;
        this.listData = res.data.data;
        this.totalNumber = res.data.data_sum;
      };
      let params = {
        page_index: this.listParam.pageIndex,
        page_size: this.listParam.pageSize,
        level_type: this.listParam.levelType,
        status: this.listParam.status,
        start_time: this.listParam.pickerTime[0],
        end_time: this.listParam.pickerTime[1],
        keyword: this.listParam.keyword,
        user_id: this.userId
      };
      this.$ajax.get("api/competition/match", {
        params,
        func: { success: success }
      });
    },
    /**
    * 搜索列表
    */
    searchFunc() {
        this.listParam.pageIndex = 1;
        this.getList();
    },
    /**
     * 重置管理列表
     */
    resetList() {
      this.listParam = Object.assign({}, deep_clone(defaultParam));
      this.getList();
    },
    /**
     * 置顶/取消置顶
     * @param {Number} val 要删除数据的 id
     */
    setTop(id) {
      let success = res => {
        this.getList();
      };
      this.$ajax.post(
        "api/competition/activity_top",
        {
          id: id
        },
        { func: { success: success } }
      );
    },
    /**
     * 赛事详情页
     * @param {Number} id 赛事 id
     */
    goDetail(id) {
      this.$router.push("/life/events/events-details/" + id);
    },
    /**
     * 发布成绩
     * @param {Number} id 赛事 id
     */
    releaseResults(id) {
      this.eventId = id;
    },
    //上传成功的事件
    fileSuccess(rootFile, file, message, chunk) {
      var mess = eval("(" + message + ")");
      mess = handleResponseData(mess);
      let success = res => {
        this.$refs.uploader.uploader.removeFile(file); //上传文件列表隐藏
        this.getList();
        this.$message.success(res.msg);
      };
      var params = {
        id: this.eventId,
        name: mess.data.file_name,
        path: mess.data.file_path,
        file_type: mess.data.file_type,
        create_id: this.$g.user_id
      };
      this.$ajax.post("api/competition/match_file", params, {
        func: { success: success }
      });
    },
    fileFail(rootFile, file, message, chunk) {
      var mess = eval("(" + message + ")");
      if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
        let callbcak = data => {
          this.uploadRetryTimes--;
          this.$refs.uploader.uploader.retry(file);
        };
        this.get_access_token(callbcak);
      } else {
        this.$message.error(mess.msg);
      }
    },
    /**
     * 导出名单Excel表
     *  @param {Number} id 赛事 id
     */
    getAllData(id) {
      let params = {
        competition_id: id
      };
      let success = res => {
          if(res.data.length>0){
             this.exportExcel(res.data);
          }else{
              this.$message.info("还没有人报名~");
          }
      };
      this.$ajax.get("api/competition/match_user", {
        params: params,
        func: { success: success }
      });
    },
    /**
     * 导出Excel表
     * @param {Array} allData 全部数据
     */
    exportExcel(allData) {
      if (allData.length === 0) {
        this.$message.warning("导出的数据为空！");
        return false;
      }

      let exportList = [];
      const defaultCellStyle = {
        font: { name: "Verdana", sz: 14, color: "FF00FF88" },
        fill: { fgColor: { rgb: "FFFFAA00" } }
      };
      const wopts = {
        bookType: "xlsx",
        bookSST: false,
        type: "binary",
        defaultCellStyle: defaultCellStyle,
        showGridLines: false
      };
      const wb = { SheetNames: ["Sheet1"], Sheets: {}, Props: {} };

      for (let i = 0; i <= allData.length - 1; i++) {
        // 每个名单表格中必有的选项
        let baseObj = {
          用户: allData[i].user_name,
          账号: allData[i].user_number,
          学段年级班级:
            allData[i].org_name == "" ? "未绑定" : allData[i].org_name,
          角色: allData[i].role_name,
          状态: allData[i].status_txt
        };
        //表格中自定义项(每个报名自定义部分)
        let obj = {};
        allData[i].information.forEach((item, inx) => {
          let keyn = JSON.parse(item).name;
          let valn = JSON.parse(item).value;
          obj[keyn] = valn;
          // 固定选项和自定义选项合并到一个对象，丢进exportList数组
          exportList[i] = Object.assign(baseObj, obj);
        });
      }
      // console.log(exportList, 1);
      wb.Sheets["Sheet1"] = XLSX.utils.json_to_sheet(exportList);
      wb.Sheets["Sheet1"]["!cols"] = [
        {
          wpx: 110
        },
        {
          wpx: 110
        },
        {
          wpx: 120
        },
        {
          wpx: 110
        },
        {
          wpx: 80
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        }
      ];

      //创建二进制对象写入转换好的字节流
      let tmpDown = new Blob([this.str2Buffer(XLSX.write(wb, wopts))], {
        type: "application/octet-stream"
      });
      FileSaver.saveAs(tmpDown, `报名名单-表格.xlsx`);
    },
    /**
     * 字符串转类型化数组
     * @param {String} str 字符串
     */
    str2Buffer(str) {
      if (typeof ArrayBuffer !== "undefined") {
        let buf = new ArrayBuffer(str.length);
        let view = new Uint8Array(buf);

        for (let i = 0; i != str.length; i += 1) {
          view[i] = str.charCodeAt(i) & 0xff;
        }
        return buf;
      } else {
        let buf = new Array(str.length);

        for (let i = 0; i != str.length; i += 1) {
          buf[i] = str.charCodeAt(i) & 0xff;
        }
        return buf;
      }
    },
    /**
     * 删除数据
     * @param {Number/Array} 要删除数据的 id
     */
    deleteData(id) {
      let success = res => {
        this.$message.success(res.msg);
        this.getList();
      };
      let fail = res => {
        this.$message.error(res.msg);
        this.getList();
      };
      let params = {
        id: id,
        type: 2,
        user_id: this.$g.user_id
      };

      this.$ajax.delete("api/competition/match", {
        params,
        func: { success: success, fail: fail }
      });
    },
    /**
     * 是否删除该数据
     * @param {Number} val 要删除数据的 id
     */
    delActivity(val) {
      let yes = res => {
        this.deleteData(val);
      };
      let cancel = res => {};
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "删除后不可恢复，确认删除吗？"
      });
    },
    /**
     * 是否确定批量删除
     */
    dleteAllConfirm() {
      if (this.selected.length === 0) {
        this.$message.warning("请选择要删除的项");
        return false;
      }

      let yes = res => {
        let ids = [];
        this.rowLen = this.selected.length;
        this.selected.forEach(item => {
          ids.push(item.id);
        });

        this.deleteData(ids);
      };
      let cancel = res => {};

      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定要删除选中的项吗？"
      });
    },
    /**
     * 列表数据多选
     * @param {Array} val 选中数据的数组
     */
    tableSelectionChange(val) {
      this.selected = val;
    },
    /**
     * 设置每页中显示的数据数量
     * @param {Number} val 每页数据条数
     */
    changeCurrentSize(val) {
      this.listParam.pageIndex = 1;
      this.listParam.pageSize = val;
      this.getList();
    },
    /**
     * 切换到第几页数据
     * @param {Number} val 页数
     */
    changeCurrentPage(val) {
      this.listParam.pageIndex = val;
      this.getList();
    }
  }
};
</script>

<style lang="scss">
.events-management {
  .open-width {
    .el-date-editor {
      width: 100%;
      vertical-align: middle;
    }
  }
  .release-results {
    display: inline;
  }
  .uploader {
    display: inline;
    .uploader-drop {
      display: inline;
      border: none;
      background-color: transparent;
      padding: 0;
      .uploader-btn {
        color: #409eff;
        border: none;
        &:hover {
          color: #66b1ff;
          background-color: transparent;
        }
      }
    }
  }
}
</style>